/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package converter;

import DAO.DAOUsuario;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import model.Usuario;

/**
 *
 * @author Jefferson
 */
public class ConverterUsuario implements Converter {
    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
        if ((value == null) || (value.length() == 0)) {
            return null;
        }
        DAOUsuario dao = DAOUsuario.getInstance();
        return dao.carregar(getID(value), Usuario.class);
    }

    Integer getID(String value) {
        Integer id;
        id = Integer.valueOf(value);
        return id;
    }

    String getStringID(Integer value) {
        StringBuilder sb = new StringBuilder();
        sb.append(value);
        return sb.toString();
    }
    
    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof Usuario) {
            Usuario o = (Usuario) value;
            return getStringID(o.getId());
        } 
        else {
            throw new IllegalArgumentException("objeto " + value + " possui o tipo "
                + value.getClass().getName()
                + "; tipo esperado: Usuario.");
        }
    }
}